﻿using SAP.Middleware.Connector;
using System;
using System.Collections;

namespace NCo3Demo {
    public class SAPService {
        // get information from company code
        public ArrayList GetCocdInfo(String cocd) {
            var list = new ArrayList();
            RfcDestination dest = DestinationProvider.GetSAPDestination();
            RfcRepository repository = dest.Repository;

            IRfcFunction fm = repository.CreateFunction("BAPI_COMPANYCODE_GETDETAIL");
            fm.SetValue("COMPANYCODEID", cocd); // fill parameter
            fm.Invoke(dest); // call function

            // BAPI_COMPANYCODE_GETDETAIL returns a structure named COMPANYCODE_DETAIL
            // which contains the information of the company code
            IRfcStructure cocdDetail = fm.GetStructure("COMPANYCODE_DETAIL");
            list = SAPUtils.ToArrayList(cocdDetail); // convert to ArrayList

            return list;
        }

        public ArrayList GetCocdInfo2(String cocd) {
            var list = new ArrayList(); // return value

            RfcDestination dest = DestinationProvider.GetSAPDestination();
            RfcFunctionMetadata fmMeta = dest.Repository.GetFunctionMetadata("BAPI_COMPANYCODE_GETDETAIL");
            IRfcFunction fm = fmMeta.CreateFunction();

            fm.SetValue("COMPANYCODEID", cocd);
            fm.Invoke(dest);

            IRfcStructure cocdDetail = fm.GetStructure("COMPANYCODE_DETAIL");
            list = SAPUtils.ToArrayList(cocdDetail);

            return list;
        }

        public void ListFunctionParameters(String fmName) {
            RfcDestination dest = DestinationProvider.GetSAPDestination();
            IRfcFunction fm = dest.Repository.CreateFunction(fmName);

            for (int i = 0; i < fm.ElementCount; i++) {
                RfcElementMetadata elementMeta = fm.GetElementMetadata(i);
                if (elementMeta.GetType() == typeof(RfcParameterMetadata)) {
                    RfcParameterMetadata param = (RfcParameterMetadata)elementMeta;
                    Console.WriteLine("Name: " + param.Name);
                    Console.WriteLine("Data type: " + param.DataType);
                    Console.WriteLine("UcLength: " + param.UcLength);
                    Console.WriteLine("NucLength: " + param.NucLength);
                    Console.WriteLine("Documentation: " + param.Documentation);
                    Console.WriteLine("--------------------------");
                }
            }
        }
    }
}
